import React, { useEffect, useState } from "react";
import { Space, Table, Tag } from "antd";
import { Button, Modal } from "antd";
import { Pagination } from "antd";
import instance from "../../api/request";
import { Checkbox, Form, Input } from "antd";
import { message, Popconfirm } from "antd";

function Index() {
  
  // 清空
  const [serchFrom] = Form.useForm();
  const qinkong = () => {
    serchFrom.resetFields();
  };
  // 搜索
  const [keyword, setKeyword] = useState("");
  const Finish = (values) => {
    console.log("Success:", values);
    setKeyword(values.keyword);
  };
  const FinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  const [title, setTitle] = useState("");
  // 新增
  const [xinFrom] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
    xinFrom.resetFields();
    setTitle("新增");
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // 编辑
  const [editId, setEditId] = useState();
  const edit = (record) => {
    setTitle("编辑");
    setIsModalOpen(true);
    setEditId(record.id);
    // 修正表单字段名称匹配
    xinFrom.setFieldsValue({
      title: record.title,
      content: record.content
    });
  };

  const onFinish = (values) => {
    const commonData = {
      title: values.title,
      content: values.content,
      tagList: values.tagList,
      categoryList: values.categoryList,
      authorId: 47529555
    };
    if (title === "新增") {
      console.log("Success:", values);

      instance
        .post(
          "/article",
          commonData,
          {
            headers: {
              Authorization:
                "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imp5a2wiLCJ1c2VySWQiOjQ3NTI5NTU1LCJyb2xlIjoxLCJpYXQiOjE3Mzk3OTQyNDIsImV4cCI6MTc0MjM4NjI0Mn0.O7KlsogMjr6YowtOXKGrEaldz5kjKHWQCn3FGvRd1bA"
            }
          }
        )
        .then((res) => {
          console.log(res);
          alert("新增成功");
          getdata();
          setIsModalOpen(false);
        });
    } else {
      instance
        .put(`/article/${editId}`, commonData, {
          headers: {
            Authorization:
              "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imp5a2wiLCJ1c2VySWQiOjQ3NTI5NTU1LCJyb2xlIjoxLCJpYXQiOjE3Mzk3OTQyNDIsImV4cCI6MTc0MjM4NjI0Mn0.O7KlsogMjr6YowtOXKGrEaldz5kjKHWQCn3FGvRd1bA"
          }
        })
        .then((res) => {
          console.log("eiltd", res);
          alert("编辑成功");
          getdata();
          setIsModalOpen(false);
        });
    }
  };
  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  // 渲染列表
  const [list, setList] = useState([]);
  const getdata = () => {
    instance
      .get("/article/list", {
        params: {
          keyword
        }
      })
      .then((res) => {
        console.log(res);
        setList(res.data.rows);
      });
  };
  useEffect(() => {
    getdata();
  }, [keyword]);
  const columns = [
    {
      title: "id",
      dataIndex: "id",
      key: "id",
      render: (text) => <a>{text}</a>
    },
    {
      title: "消息名称",
      dataIndex: "title",
      key: "title"
    },
    {
      title: "消息描述",
      dataIndex: "content",
      key: "content"
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt"
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => edit(record)}>编辑</Button>
          {/* <Popconfirm
            title="删除"
            description="您确定删除吗？"
            onConfirm={() => confirm(record.id)}
            onCancel={cancel}
            okText="确定"
            cancelText="取消"
          >
            <Button danger>删除</Button>
          </Popconfirm> */}
          <Button>查看</Button>
        </Space>
      )
    }
  ];

  return (
    <div>
      {/* 搜索 */}
      <Form
        form={serchFrom}
        name="basic"
        layout="inline"
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={Finish}
        onFinishFailed={FinishFailed}
        autoComplete="off"
      >
        <Form.Item label="消息名称" name="keyword">
          <Input />
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
          <Button type="primary" htmlType="submit" onClick={qinkong}>
            清空
          </Button>
        </Form.Item>
      </Form>
      {/* 新增 */}
      <Button onClick={() => showModal()}>新增</Button>
      <Modal
        title={title}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={xinFrom}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="消息名称"
            name="title"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="消息描述"
            name="content"
            rules={[{ required: true, message: "Please input your password!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Table
        columns={columns}
        dataSource={list}
        pagination={{
          total: list.length,
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 5,
          showTotal: (total) => `Total ${total} items`
        }}
      />
    </div>
  );
}

export default Index;